<?php
/**
 * Created by PhpStorm.
 * User: 任旭明 <846723340@qq.com>
 * Date: 2018/11/6
 * Time: 10:21
 */

namespace app\index\controller;

use app\model\OrderInfoModel;
use app\model\UserModel;
use think\cache\driver\Redis;
use think\Controller;
use app\model\ProductInfoModel;

class cart extends Auth
{

    protected $uid;

    protected $suffix;

    private $length = 6;

    static private $redis;

    static private $cart = 'cartId_';

    static private $numb = 'cartNum_';

    static protected $result = [
        'code' => 400,
        'info' => 'Param error',
    ];


    public function _initialize()
    {
        parent::_initialize();
        $this->suffix = substr($this->uid, -1, 1);
        self::$redis = (new Redis());
    }

    /**
     * @var 购物车
     */
    public function index($limit)
    {
        $cartArray = $this->getUserCart((int)$limit);
        if ($cartArray) {
            $pidStr = join(',', array_keys($cartArray));
            if ($pidStr) {
                $list = (new ProductInfoModel())->selectAll("id in({$pidStr})", 'id, product_id, name, size, color, member_price, price, url');
            }
            // dump($list);die;
            $list = !empty($list) ? $this->_toArray($list, $cartArray) : [];
            if (!(int)$limit && $list) {
                $mark = (new UserModel())->getValue("id = {$this->uid}", 'is_vip');
                $this->assign('mark', $mark);
                $this->assign('list', $list);

                return $this->fetch();
            } elseif ($limit && $list) {
                return json_encode($list);
            } elseif (!$list) {
                return json_encode([]);
            }
        }
        return $this->fetch('cart_empty');
    }

    /**
     * @var 加入购物车
     */
    public function addToCart()
    {
        $gid = (int)input('post.gid') ? (int)input('post.gid') : 0;
        $pid = (int)input('post.pid') ? (int)input('post.pid') : 0;
        $num = (int)input('post.num') ? (int)input('post.num') : 1;
        if ($gid && $pid) {
            $info = (new ProductInfoModel('', '', '', 'sy_product p', 'p.id = pi.product_id', '', 'pi'))->findOne("pi.id = {$pid} and pi.product_id = {$gid}", 'pi.stock, p.sale_id');
            if ($info && $info['stock'] == 0) {
                self::$result['code'] = 202;
                self::$result['info'] = '库存不足!';
            } elseif ($info) {
                if ($info['sale_id']) {
                    $buyRecord = (new OrderInfoModel($this->suffix))->getValue("gid = {$gid} and ouid = {$this->uid}", 'id');
                }
                $cartArr = self::getUserCart();
                if ($info['sale_id'] && !empty($buyRecord)) {
                    self::$result['code'] = 202;
                    self::$result['info'] = '该商品限购你已经买过了哦!';
                } elseif (!empty($cartArr[$pid]) && $info['sale_id']) {
                    self::$result['code'] = 202;
                    self::$result['info'] = '该商品已在购物车且只能购买一件!';
                } elseif (count($cartArr) >= 99 && empty($cartArr[$pid])) {
                    self::$result['code'] = 202;
                    self::$result['info'] = '已经达到购物车最大数量!';
                } elseif (empty($cartArr) || empty($cartArr[$pid])) {
                    self::$result = self::_create($cartArr, $pid, $num);
                } elseif (!empty($cartArr[$pid])) {
                    self::$result = self::_number($cartArr, $pid, ++$cartArr[$pid]);
                }
            }
        }
        return json_encode(self::$result);
    }


    /**
     * @var 存入购物车
     */
    private function _create($cartArr, $pid, $num)
    {
        $cartArr[$pid] = $num;
        $result = self::_save($cartArr);
        return $result;
    }

    /**
     * @var 增加数量
     */
    private function _number($cartArr, $pid, $num)
    {
        $cartArr[$pid] = $num;
        $result = self::_save($cartArr);
        return $result;
    }

    /**
     * @var 获取购物车商品和数量数组
     */
    private function getUserCart($limit = '')
    {
        $pidStr = self::$redis->get(self::$cart . $this->uid);
        $numStr = self::$redis->get(self::$numb . $this->uid);
        if ($limit || $limit === 0 && $pidStr && $numStr) {
            $pidArray = array_slice(array_reverse(explode(',', self::$redis->get(self::$cart . $this->uid))), $this->length * $limit, $this->length);
            $numArray = array_slice(array_reverse(explode(',', self::$redis->get(self::$numb . $this->uid))), $this->length * $limit, $this->length);
        } elseif (!$limit && $limit !== 0 && $pidStr && $numStr) {
            $pidArray = self::$redis->get(self::$cart . $this->uid) ? explode(',', self::$redis->get(self::$cart . $this->uid)) : [];
            $numArray = self::$redis->get(self::$numb . $this->uid) ? explode(',', self::$redis->get(self::$numb . $this->uid)) : [];
        }
        $arr = [];
        if (!empty($pidArray) && !empty($numArray)) {
            $arr = array_combine($pidArray, $numArray);
        }
        return $arr;
    }

    /**
     * @var 改变数量
     */
    public function number()
    {
        $gid = (int)input('post.gid') ? (int)input('post.gid') : 0;
        $pid = (int)input('post.pid') ? (int)input('post.pid') : 0;
        $num = (int)input('post.num') ? (int)input('post.num') : 0;
        if ($gid && $pid && $num) {
            $info = (new ProductInfoModel('', '', '', 'sy_product p', 'p.id = pi.product_id', '', 'pi'))->findOne("pi.id = {$pid} and pi.product_id = {$gid}", 'pi.stock, p.sale_id');
            if ($info && $info['stock'] == 0 && $num > $info['stock']) {
                self::$result['code'] = 202;
                self::$result['info'] = '库存不足!';
            } elseif ($info && $info['sale_id']) {
                self::$result['code'] = 202;
                self::$result['info'] = '商品限购';
            } elseif ($info) {
                $cartArr = self::getUserCart();
                if ($cartArr[$pid]) {
                    self::$result = self::_number($cartArr, $pid, $num);
                }
            }
        }
        return json_encode(self::$result);
    }

    /**
     * @var 删除
     */
    public function delete($pid)
    {
        if ((int)$pid) {
            $cartArr = self::getUserCart();
            if ($cartArr && $cartArr[(int)$pid]) {
                unset($cartArr[(int)$pid]);
                self::_save($cartArr);
                self::$result['code'] = 202;
                self::$result['info'] = '删除成功!';
            }
        }
        return json_encode(self::$result);
    }

    /**
     * @var 删除购物车数组
     */
    public function deleteArr($pidArr, $id)
    {
        if (is_array($pidArr)) {
            $cartArr = self::getUserCart();
            foreach ($pidArr as $v) {
                unset($cartArr[$v]);
            }
            self::$redis->set(self::$cart . $id, join(',', $cartArr));
        }
        return true;
    }

    /**
     * @var 存储
     */
    private function _save($cartArr)
    {
        $pidStr = join(',', array_keys($cartArr));
        $numStr = join(',', array_values($cartArr));
        self::$redis->set(self::$cart . $this->uid, $pidStr);
        self::$redis->set(self::$numb . $this->uid, $numStr);
        return $result = [
            'code' => 200,
            'info' => '添加成功'
        ];
    }


    /**
     * @var 遍历时加入数量
     */
    private function _toArray($list, $num)
    {
        foreach ($list as $k => $v) {
            if (array_key_exists($v['id'], $num)) {
                $list[$k]['num'] = $num[$v['id']];
            }
        }
        return $list;
    }

    /**
     * @var 遍历时取出数量
     */
    private function _getNum($list, $cart)
    {
        foreach ($list as $k => $v) {
            if (array_key_exists($v['pid'], $cart)) {
                $list[$k]['num'] = $cart[$v['pid']];
            }
        }
        return $list;
    }

    /**
     * @var 调用付款页
     */
    public function pay()
    {


        $goodsList = is_array(json_decode(input('get.goodslist'), true)) ? json_decode(input('get.goodslist'), true) : [];
        if ($goodsList) {
            $gidArray = array_column($goodsList, 'gid');
            $pidArray = array_column($goodsList, 'pid');
            $goodsStatus = count($gidArray) == count($pidArray) ? !empty($gidArray) : false;
            if ($goodsStatus) {
                $cartArray = $this->getUserCart();
                $userInfo = (new UserModel('', '', '', 'sy_address a', 'a.user_id = u.id', 'left', 'u'))->findOne("u.id = {$this->uid} and a.default_address = 1", 'u.is_vip, a.mobile, a.consignee, a.province, a.city, a.country, a.detail, a.id');
                $field = 'pi.product_id , pi.stock, pi.id, pi.name, pi.url, pi.color, pi.size, p.sale_id,';
                if ($userInfo && $userInfo['is_vip'] == 1) {
                    $field .= ' pi.member_price as price ';
                } elseif ($userInfo && $userInfo['is_vip'] === 0) {
                    $field .= ' pi.price  as price';
                }
                $goodsInfoList = (new ProductInfoModel('', '', '', 'sy_product p', 'p.id = pi.product_id', '', 'pi'))->selectAll('pi.id in(' . join(', ', $pidArray) . ')', $field);
                $stockState = $this->_checkGoodsStock($goodsInfoList, $cartArray, $gidArray);
                if (is_array($stockState)) {
                    $Coupon = (new ProductInfoModel('sy_coupon'))->selectAll("uid = {$this->uid}", '*');
                    $this->assign('userInfo', $userInfo);
                    $this->assign('coupon', $Coupon);
                    if (empty($stockState['sale'])) {
                        $this->assign('sale', 0);
                    } else {
                        $this->assign('sale', 1);
                    }
                    $userInfo['province'] ? $address = ['consignee' => $userInfo['consignee'], 'province' => $userInfo['province'], 'city' => $userInfo['city'], 'country' => $userInfo['country'], 'detail' => $userInfo['detail'], 'mobile' => $userInfo['mobile'], 'id' => $userInfo['id']] : [];
                    $this->assign('address', $address);
                    return $this->fetch('payment', ['list' => $stockState]);
                } else {
                    self::$result['code'] = 300;
                    self::$result['info'] = $stockState;
                }
            }
        }
        return json_encode(self::$result);
    }

    /**
     * @var 检查库存 提交gid参数的正确
     */
    private function _checkGoodsStock($goodsList, $cartArray, $gidArray)
    {
        $coutnPrice = 0;
        foreach ($goodsList as $k => $v) {
            if ($v['stock'] < (int)$cartArray[$v['id']]) {
                $info = "{$v['name']} 库存不足";
                return $info;
                break;
            } else {
                $goodsList[$k]['num'] = $cartArray[$v['id']];
            }

            if (!in_array($v['product_id'], $gidArray)) {
                $info = "{$v['name']} 商品错误,请稍后再试!";
                return $info;
                break;
            }
            if ($v['sale_id']) {
                $goodsList['sale'] = 1;
            }

            $coutnPrice += $v['price'];
        }
        // $goodsList['countPrice'] = $coutnPrice;
        return $goodsList;
    }


}
